package com.dynamic.mybatis.bootstrap.handler;

import com.alibaba.fastjson2.JSON;
import com.dynamic.mybatis.bootstrap.mapper.MyBaseMapper;
import com.dynamic.mybatis.core.datasource.DataSourceProperty;
import com.dynamic.mybatis.core.intercept.DynamicDataSourceHandler;
import com.dynamic.mybatis.core.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.Map;

/**
 * @Description
 * @Author xs
 * @Date 2023/5/23 13:28
 */
@Component
public class MyDataSourceHandler implements DynamicDataSourceHandler {

    @Autowired
    @Lazy
    MyBaseMapper myBaseMapper;


    @Override
    public void before(OPERATE operate, Object dataSourceKey, DataSource dataSource, DataSourceProperty property, Map<Object, Object> attributes) {
        System.err.println("before dataSource handle.   " + operate + "   " + dataSourceKey);
    }

    @Override
    public void after(OPERATE operate, Object dataSourceKey, DataSource dataSource, DataSourceProperty property, Map<Object, Object> attributes) {
        System.err.println("after dataSource handle.   " + operate + "   " + dataSourceKey);
        Map<String, Object> data = JSON.parseObject(JSON.toJSONString(property));
        if (StringUtils.isNotBlank(property.getUid())) {
            data.put("id", Integer.valueOf(property.getUid()));
        }
        myBaseMapper.saveDataSource(data);
    }
}